`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    15:28:39 04/07/2014 
// Design Name: 
// Module Name:    loopback 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module uarts(
	clk,
	rst,
	rs232_tx,
	rs232_rx,
	tx_buffer,
	rx_buffer,
	write_buffer,
	read_buffer,
	tx_full,
	rx_data_present
);

	input clk;
	input rst;
	input rs232_rx;
	output rs232_tx;
	input tx_buffer;
	output rx_buffer;
	input write_buffer;
	input read_buffer;
	output tx_full;
	output rx_data_present;
	
	
	// Implement the 16x bit rate counter
	// for the uart transmit and receive.
	// The system clock is 100 MHz, and the
	// desired baud rate is 9600.  Use
	// the following formula to calculate 
	// the terminal count value.
	// maximum baud_count = (frequency/(16* baud_rate))
	// Note when baud_count reaches maximum_baud_count, 
	// then we need to reset baud_count and generate 
	// a en_16_x_baud pulse.

	reg [9:0] baud_count;
	reg en_16_x_baud;
	wire [7:0] tx_buffer;
	wire [7:0] rx_buffer;
	wire write_buffer;
	wire read_buffer;
	wire tx_full;
	wire rx_data_present;
	
	uart_tx transmit(
		.data_in(tx_buffer), 
		.write_buffer(write_buffer),
		.reset_buffer(!rst),
		.en_16_x_baud(en_16_x_baud),
		.serial_out(rs232_tx),
		.buffer_full(tx_full),
		.buffer_half_full(),
		.clk(clk)
	);

	uart_rx receive(
		.serial_in(rs232_rx),
		.data_out(rx_buffer),
		.read_buffer(read_buffer),
		.reset_buffer(!rst),
		.en_16_x_baud(en_16_x_baud),
		.buffer_data_present(rx_data_present),
		.buffer_full(),
		.buffer_half_full(),
		.clk(clk)
	);
	
	always @(posedge clk)
	begin
		if (!rst)
		begin
			baud_count <= 0;
			en_16_x_baud <= 0;
		end
		else
		begin
			if (baud_count == 651)  // = maximum_baud_count
			begin
				baud_count <= 0;
				en_16_x_baud <= 1;
			end
			else
			begin
				baud_count <= baud_count + 1;
				en_16_x_baud <= 0;
			end
		end
	end
	
endmodule